package fr.upmc.utils;

import java.io.IOException;

import javax.servlet.http.*;

public class SessionTracker {
	
	//If user is authenticated, created implicitly a session for it.
	public static Boolean authenticate(String name, String pass, HttpServletRequest req){
		
		//TODO: change that
		if(name != null && name.length()>0 && name.equals(pass)){
			//TRUE: creates a new session
			HttpSession session = req.getSession(true);
			session.setAttribute("user", name);
			return true;
		}
		
		return false;
	}
	
	public static Boolean isUserConnected(HttpServletRequest req){
		HttpSession session = req.getSession(false);
		
		try {
			String user = (String)session.getAttribute("user");
			if(user != null && user.length()>0)
				return true;
		} catch (Exception e) {
			return false;
		}
		
		return false;
	}
	
	public static void eraseSession(HttpServletRequest req){
		HttpSession session = req.getSession(false);
		session.invalidate();
	}
	
	public static void redirectToHome(HttpServletResponse response){
		try {
			response.sendRedirect("index.html?error=auth");
		} catch (IOException e) {
			;
		}
	}
}
